
//  AsyncConnection.m
//  MedicineBox
//
//  Created by dllo on 15/8/22.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "AsyncConnection.h"
#import "AFNetworking.h"
#import "Reachability.h"
#import "SaveTools.h"
@interface AsyncConnection ()<NSURLConnectionDataDelegate>
@property (nonatomic, copy) void (^block)(id);
@property (nonatomic, copy) NSString *filePath;


@end

@implementation AsyncConnection

-(void)dealloc
{
    Block_release(_block);
    [_filePath release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        
    }
    return self;
}

#pragma mark - 
#pragma mark 判断是否有网络

+ (BOOL)judgeConnection
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus curStatus = [reach  currentReachabilityStatus];
    if (curStatus == NotReachable) {
        return NO;   //没有网络
    }else if (curStatus == ReachableViaWWAN)
    {
        return YES;
    }else if (curStatus == ReachableViaWiFi)
    {
        return YES;
    }
    return NO;
}


+ (instancetype)asyncConnectionWithUrl:(NSString *)urlStr name:(NSString *)name parameters:(NSDictionary *)parameters block:(void(^)(id data))block get:(NSString *)type
{
    if (parameters != nil) {
        NSString *par = @"";
        for (NSString *key in parameters) {
            if ([par length] == 0) {
                par = [NSString stringWithFormat:@"?%@=%@", key,[parameters objectForKey:key]];
            }else
            {
                par = [NSString stringWithFormat:@"%@&%@=%@", par, key, [parameters objectForKey:key]];
            }
        }
        urlStr = [NSString stringWithFormat:@"%@%@",urlStr, par];
        NSLog(@"%@", urlStr);
    }
    
    AsyncConnection *asy = [[AsyncConnection alloc] init];
    asy.block = block;
    [asy startConnection:urlStr name:name type:type];
    return [asy autorelease];
}

- (void)startConnection:(NSString *)url name:(NSString *)name type:(NSString *)type
{
    BOOL judge = [AsyncConnection judgeConnection];
    if (judge) {
        if ([type isEqualToString:@"get"]) {
            
            AFHTTPRequestOperationManager *man = [AFHTTPRequestOperationManager manager];
            man.responseSerializer = [AFHTTPResponseSerializer serializer];
            [man GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [SaveTools saveWithName:name directory:NSLibraryDirectory value:responseObject];
                id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                self.block(data);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@", error);
            }];
            
        } if ([type isEqualToString:@"post"]) {
            
            AFHTTPRequestOperationManager *man = [AFHTTPRequestOperationManager manager];
            man.responseSerializer = [AFHTTPResponseSerializer serializer];
            [man POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [SaveTools saveWithName:name directory:NSLibraryDirectory value:responseObject];
                id data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                self.block(data);
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                NSLog(@"post请求错误");
                
            }];
            
        }
        
    }
    else //没有网判断本地是否有数据
    {
        NSString *path = [SaveTools pathWithName:name directory:NSLibraryDirectory];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:path]) {
            NSData *data = [NSData dataWithContentsOfFile:path];
            id reciveData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.block(reciveData);
            
        }else
        {
            if (![url isEqualToString:@"http://openapi.ypt.langma.cn/yws/?json=%7B%0A%20%20%22op_type%22%20%3A%201003%2C%0A%20%20%22c_ver%22%20%3A%20%224.0.0%22%2C%0A%20%20%22c_type%22%20%3A%200%2C%0A%20%20%22uid%22%20%3A%200%2C%0A%20%20%22cid%22%20%3A%200%0A%7D"]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有网络" message:@"请连接网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
        
        }
    }
    
}


@end
